package com.wmh.baseservice.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.user.pojo.UsEvaluate;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.UsVegetableOrder;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import com.wmh.baseservice.user.service.UsVegetableOrderService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wmh.baseservice.user.service.UsEvaluateService;

import java.util.List;

/**
 * @author wmh generator
 * @since 2022-02-02
 */
@Api(tags = "用户端-评价相关接口")
@RestController
@RequestMapping(value = "user/usEvaluate", produces = "text/plain;charset=utf-8")
public class UsEvaluateController {

    @Resource
    private UsEvaluateService usEvaluateService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private UsVegetableOrderService usVegetableOrderService;
    @Resource
    private UsInfoService usInfoService;

    @ApiOperation("添加评价")
    @PostMapping("add")
    @ParameterVerify(notNull = {"usEvaluate.type", "usEvaluate.content"})
    public String add(UsEvaluate usEvaluate) {
        Long usId = (Long) request.getAttribute("usId");
        QueryWrapper<UsEvaluate> eq = new QueryWrapper<UsEvaluate>().eq(UsEvaluate.ITEM_ID, usEvaluate.getItemId()).eq(UsEvaluate.US_ID, usId).eq(UsEvaluate.TYPE, usEvaluate.getType()).eq(UsEvaluate.ORDER_NUM, usEvaluate.getOrderNum());
        UsEvaluate rawEva = usEvaluateService.getOneForUpdate(eq);
        if (CommUtil.checkNull(rawEva)) {
            return ReturnBody.error("您已对该订单提交过评价，请不要重复提交");
        }
        if (usEvaluate.getType() == 4) {
            UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, usEvaluate.getOrderNum()));
            if (!CommUtil.checkNull(usGroupGoodsOrder) || (usGroupGoodsOrder.getStatus() != 5 && usGroupGoodsOrder.getStatus() != 4)) {
                return ReturnBody.error("订单状态错误");
            }
        } else if (usEvaluate.getType() == 1) {
            UsVegetableOrder usVegetableOrder = usVegetableOrderService.getOneForUpdate(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, usEvaluate.getOrderNum()));
            if (!CommUtil.checkNull(usVegetableOrder) || usVegetableOrder.getStatus() != 3) {
                return ReturnBody.error("订单状态错误");
            }
        }
        if (CommUtil.checkNull(usEvaluate.getImg())) {
            JSONArray array = JSONArray.parseArray(usEvaluate.getImg());
            if (array.size() != 0) {
                StringBuilder sb = new StringBuilder();
                array.forEach(item -> {
                    String url = Base64Util.generateImage("eva/", item.toString());
                    if (CommUtil.checkNull(url)) {
                        sb.append(url).append(",");
                    }
                });
                String img = sb.replace(sb.length() - 1, sb.length(), "").toString();
                usEvaluate.setImg(img);
            }
        }
        usEvaluate.setUsId(usId);
        usEvaluateService.add(usEvaluate);
        return ReturnBody.success();
    }

    @ApiOperation("列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "被评价的商品id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "1、果蔬 2、商品 3、土地 4、团购商品 5、平台商品", required = true),
    })
    @ParameterVerify(notNull = {"id", "type"})
    public String list(Long id, Integer type) {
        JSONObject object = new JSONObject(true);
        List<UsEvaluate> usEvaluates = usEvaluateService.listForUpdate(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.TYPE, type).eq(UsEvaluate.ITEM_ID, id));
        //求和
        double rate = usEvaluates.stream().mapToDouble(UsEvaluate::getRate).sum();
        //保留两位小数，四舍五入
        object.put("rate", (double) Math.round(rate / usEvaluates.size() * 100) / 100);
        JSONArray array = new JSONArray();
        if (usEvaluates.size() != 0) {
            usEvaluates.forEach(usEvaluate -> {
                JSONObject evaObj = new JSONObject(true);
                UsInfo usInfo = usInfoService.getByIdForUpdate(usEvaluate.getUsId());
                evaObj.put("usEvaluate", usEvaluate);
                evaObj.put("nick", usInfo.getNick());
                evaObj.put("avatar", usInfo.getAvatar());
                array.add(evaObj);
            });
            object.put("list", array);
        }
        return ReturnBody.success(object);
    }
}
